from flask import Flask, request, jsonify
import pandas as pd
from itertools import combinations

app = Flask(__name__)

# 加载模型
frequent_itemsets = pd.read_pickle('./frequent_itemsets.pkl')
rules = pd.read_pickle('./rules.pkl')

@app.route("/recommend", methods=['POST'])
def recommend():
    # 接收传过来的参数
    data = request.json.get('items', [])

    # 生成关联规则推荐
    recommendations = []
    for idx, rule in rules.iterrows():
        antecedents = list(rule['antecedents'])
        consequents = list(rule['consequents'])
        # 检查规则前件是否跟输入匹配
        if set(antecedents).issubset(set(data)):
            recommendations.extend(consequents)

    # 去重并返回结果
    recommendations = list(set(recommendations) - set(data))
    return jsonify({"recommendations": recommendations})

if __name__ == "__main__":
    app.run()

te = TransactionEncoder()
te_ary = te.fit(trsactions).transform(trsactions)
de_encoded = pd.DataFrame(te_ary, columns=te.columns_)

# 使用apriori进行分析
frequent_itemsets = apriori(de_encoded, min_support=0.1, use_colnames=True)
frequent_itemsets.sort_values(by='support', ascending=False, inplace=True)

# 生成关联规则
rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.1)
rules = rules.sort_values(by=['lift'], ascending=False)

frequent_itemsets.to_pickle("frequent_itemsets.pkl")
rules.to_pickle("rules.pkl")